﻿using Fiddler;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace FiddlerToJMeter
{
    [ProfferFormat("JMeter", "将fiddler封包导出到jmx文件")]
    public class JMeterExporter : ISessionExporter, IDisposable
    {
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary<string, object> dictOptions, EventHandler<ProgressCallbackEventArgs> evtProgressNotifications)
        {
            bool flag = true;
            string text = Utilities.ObtainSaveFilename("Export As " + sFormat, "JMeter Files (*.jmx)|*.jmx");
            bool flag2 = string.IsNullOrEmpty(text);
            bool result;
            if (flag2)
            {
                result = false;
            }
            else
            {
                bool flag3 = !Path.HasExtension(text);
                if (flag3)
                {
                    text += ".jmx";
                }
                try
                {
                    Encoding encoding = new UTF8Encoding(true);
                    JMeterTestPlan jMeterTestPlan = new JMeterTestPlan(oSessions, text);
                    StreamWriter streamWriter = new StreamWriter(text, false, encoding);
                    streamWriter.Write(jMeterTestPlan.Jmx);
                    streamWriter.Close();
                    FiddlerApplication.Log.LogString("成功导出jmx格式，信息如下：");
                    FiddlerApplication.Log.LogString("Successfully exported sessions to JMeter Test Plan");
                    FiddlerApplication.Log.LogString(string.Format("\t{0}", text));
                }
                catch (Exception ex)
                {
                    FiddlerApplication.Log.LogString("出现异常，信息如下：");
                    FiddlerApplication.Log.LogString(ex.Message);
                    FiddlerApplication.Log.LogString(ex.StackTrace);
                    flag = false;
                }
                result = flag;
            }
            return result;
        }

        public void Dispose()
        {
        }
    }
}
